const express = require("express");
const Oss = require("ali-oss");
const fs = require("fs");
const co = require("co");
const multer  = require('multer');
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'uploads/');
  },
  filename: function (req, file, cb) {
    console.log("----ok-----");

    let ext = file.originalname.split(".").reverse()[0];
    cb(null, (new Date().getTime()) + "." + ext);
  }
});
const upload = multer({ storage: storage });


const client = new Oss({
    region: 'oss-cn-beijing',
    accessKeyId: 'gYbj2O9ej7MAGoRK',
    accessKeySecret: 'qzGSqdWU8OlVr7fDHChPOGEgdKsyVP',
    bucket: 'wngc-oss'
});
const router = express.Router();


const cpUpload = upload.fields([{ name: 'file', maxCount: 1 }, { name: 'gallery', maxCount: 8 }]);
router.post('/upload', upload.single('file') , function (req, res, next) {
    console.log("ok");
    console.log(req.file);
    console.log(req.file);
    
    co(function*() {
        var result = yield client.put(req.file.filename, req.file.path);
        yield client.putACL(req.file.filename, 'public-read');
        
        fs.unlinkSync(req.file.path);
        res.json({ code: 0, result: { img_url: result.url } });
    }).catch(function(err) {
        console.log(err);
    });
        
});


module.exports = router;